import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DesignPage } from './design-page.entity';

export interface PaginatedDesignPages {
  data: DesignPage[];
  meta: {
    total: number;
    page: number;
    limit: number;
  };
}

// 新增分页接口返回类型
export interface PaginatedPages {
  data: DesignPage[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}

export interface PaginatedDesignBanners {
  data: DesignPage[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
}


@Injectable()
export class DesignService {
  constructor(
    @InjectRepository(DesignPage)
    private designPageRepository: Repository<DesignPage>,
  ) { }

  // 保存富文本
  async saveContent(title: string, content: string): Promise<DesignPage> {
    const page = this.designPageRepository.create({ title, content });
    return this.designPageRepository.save(page);
  }

  // 获取所有页面（供后台管理使用）
  // 获取分页文章列表
  async getAllPages(
    page: number = 1,
    limit: number = 10,
  ): Promise<PaginatedPages> {
    // return this.designPageRepository.find();
    const [data, total] = await this.designPageRepository.findAndCount({
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' }, // 按创建时间倒序
    });

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    };
  }

  // 根据ID获取单页（供前端网页使用）
  async getPageById(id: number): Promise<DesignPage | null> {
    const page = await this.designPageRepository.findOne({ where: { id } });
    if (!page) {
      throw new NotFoundException(`DesignPage with ID ${id} not found`);
    }
    return page;
  }

  // 保存文章百分比
  async savePercentage(id: number, percentage: number) {
    const page = await this.designPageRepository.findOne({ where: { id } });
    if (!page) {
      throw new NotFoundException(`DesignPage with ID ${id} not found`);
    }
    page.percentage = percentage;
    return this.designPageRepository.save(page);
  }

  // 切换类别显示/隐藏状态
  async toggleVisibility(id: number, visible: boolean) {
    const page = await this.designPageRepository.findOne({ where: { id } });
    if (!page) {
      throw new NotFoundException(`DesignPage with ID ${id} not found`);
    }
    page.is_visible = visible;
    return this.designPageRepository.save(page);
  }

  // 删除设计页面（需检测关联数据）
  async deletePage(id: number): Promise<void> {
    const page = await this.designPageRepository.findOne({
      where: { id },
      relations: ['category'], // 加载关联的类别（可选，根据业务需求）
    });

    if (!page) {
      throw new NotFoundException(`DesignPage with ID ${id} not found`);
    }

    // 检测是否有其他关联数据（示例：假设有评论表关联）
    // const hasComments = await this.commentRepository.exists({ where: { pageId: id } });
    // if (hasComments) {
    //   throw new ConflictException('Cannot delete page with associated comments');
    // }

    // 如果没有关联数据，直接删除
    await this.designPageRepository.delete(id);
  }


  // 获取可见类别（供前端调用）
  async getVisiblelPages() {
    return this.designPageRepository.find({ where: { is_visible: true } });
  }


  async getPagesByCategory(
    categoryId: number,
    page: number = 1,
    limit: number = 10,
  ): Promise<PaginatedDesignPages> {
    const [data, total] = await this.designPageRepository.findAndCount({
      where: { category_id: categoryId },
      skip: (page - 1) * limit, // 动态计算偏移量
      take: limit, // 动态设置每页数量
      // select: ['id', 'title', 'cover_img', 'summary', 'createdAt'],
    });

    return { data, meta: { total, page, limit } };
  }

  async createPage(
    title: string,
    content: string,
    category_id: number,
    cover_img?: string,
    cover_images?: any,
    is_visible?: boolean,
    summary?: string,
  ): Promise<DesignPage> {
    const page = this.designPageRepository.create({
      title,
      content,
      category_id: category_id,
      cover_img: cover_img,
      cover_images: cover_images,
      is_visible: is_visible,
      summary,
    });
    return this.designPageRepository.save(page);
  }

  async updatePage(
    id: number,
    updates: {
      title: string,
      content: string,
      category_id: number,
      cover_img?: string,
      cover_images?: any,
      is_visible?: boolean,
      summary?: string,
    }
  ): Promise<DesignPage> {
    const page = await this.designPageRepository.findOne({ where: { id } });
    if (!page) {
      throw new NotFoundException(`Category with ID ${id} not found`);
    }

    // 合并更新字段（保留未修改的原始值）
    const updatedPage = this.designPageRepository.merge(page, updates);
    return this.designPageRepository.save(updatedPage);
  }

}
